import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import org.json.JSONObject;
import javax.servlet.annotation.WebServlet;

@WebServlet("/get_book")
public class GetBook extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setContentType("application/json;charset=UTF-8");
        String number = request.getParameter("number");

        String url = "jdbc:mysql://101.37.236.199:3306/linux_exam";
        String user = "root";
        String password = "1qaz@WSX#EDC";

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            try (Connection conn = DriverManager.getConnection(url, user, password)) {
                String sql = "SELECT * FROM t_book WHERE number=?";
                PreparedStatement stmt = conn.prepareStatement(sql);
                stmt.setString(1, number);
                ResultSet rs = stmt.executeQuery();
                if (rs.next()) {
                    JSONObject obj = new JSONObject();
                    obj.put("number", rs.getString("number"));
                    obj.put("name", rs.getString("name"));
                    obj.put("author", rs.getString("author"));
                    response.getWriter().write(obj.toString());
                } else {
                    response.getWriter().write("{}");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{\"error\":\"" + e.getMessage() + "\"}");
        }
    }
}
